import request from '@/utils/request'
import type { FinanceRecord } from '@/types'
import { mockFinanceAPI } from '@/mock/api'

// 是否启用Mock模式
const ENABLE_MOCK = import.meta.env.VITE_ENABLE_MOCK !== 'false'

// 获取财务记录列表
export const getFinanceList = (params: any) => {
  if (ENABLE_MOCK) {
    return mockFinanceAPI.getList(params)
  }
  return request({
    url: '/finance/list',
    method: 'get',
    params
  })
}

// 获取财务记录详情
export const getFinanceDetail = (id: string) => {
  if (ENABLE_MOCK) {
    return Promise.resolve({
      code: 200,
      data: { id, description: '财务记录详情' },
      message: '获取成功'
    })
  }
  return request({
    url: `/finance/${id}`,
    method: 'get'
  })
}

// 创建财务记录
export const createFinanceRecord = (data: Partial<FinanceRecord>) => {
  if (ENABLE_MOCK) {
    return mockFinanceAPI.create(data)
  }
  return request({
    url: '/finance',
    method: 'post',
    data
  })
}

// 更新财务记录
export const updateFinanceRecord = (id: string, data: Partial<FinanceRecord>) => {
  if (ENABLE_MOCK) {
    return mockFinanceAPI.update(id, data)
  }
  return request({
    url: `/finance/${id}`,
    method: 'put',
    data
  })
}

// 删除财务记录
export const deleteFinanceRecord = (id: string) => {
  if (ENABLE_MOCK) {
    return mockFinanceAPI.delete(id)
  }
  return request({
    url: `/finance/${id}`,
    method: 'delete'
  })
}

// 获取财务统计
export const getFinanceStats = (params?: any) => {
  if (ENABLE_MOCK) {
    return mockFinanceAPI.getStats()
  }
  return request({
    url: '/finance/stats',
    method: 'get',
    params
  })
}

// 获取收支趋势
export const getFinanceTrend = (params: any) => {
  if (ENABLE_MOCK) {
    return mockFinanceAPI.getTrend(params)
  }
  return request({
    url: '/finance/trend',
    method: 'get',
    params
  })
}

// 导出财务报表
export const exportFinanceReport = (params: any) => {
  if (ENABLE_MOCK) {
    // 创建一个模拟的Excel文件
    const content = '财务报表数据'
    const blob = new Blob([content], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    })
    return Promise.resolve(blob)
  }
  return request({
    url: '/finance/export',
    method: 'get',
    params,
    responseType: 'blob'
  })
}
